<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{porp:'timeOfEntry',order:'ascending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="图片">
            <template #default="{row}">
              <img :src="row.staffPhoto" style="width:100%" alt="">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formOfEmploymentFormat(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" />
          <!-- <el-table-column label="账户状态" prop=""/> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <!-- 路径传参 -->
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <!-- 查询参数  -->
              <!-- <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button> -->
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button allow="'delete'" type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-size="size"
            layout="prev, pager, next"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增员工的弹层 -->
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="resetForm">
        <addEmpDialog ref="empFrom" @close="hCancel" />
      </el-dialog>
      <!-- 给员工分配角色的弹层 -->
      <el-dialog
        v-if="roleShowDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        title="角色分配"
        :visible.sync="roleShowDialog"
      >
        <assignRole :id="curId" @success="hRolesSuccessAssign" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import addEmpDialog from '@/views/employees/empDialog.vue'
import { getEmployes, delEmployes } from '@/api/employees'
import EmployessEnum from '@/constant/employees'
import assignRole from './assignRole.vue'
// console.log(EmployessEnum.hireType)
// 优化枚举  forEach 用法
// const hireType = {}
// EmployessEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })

// reduce 的用法
const hireType = EmployessEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})

// console.log(hireType)
export default {
  name: 'Employees',
  components: { addEmpDialog, assignRole },
  data() {
    return {
      roleShowDialog: false,
      showDialog: false,
      page: 1,
      size: 5,
      list: [], // 存储数据列表
      total: 0,
      curId: ''
    }
  },
  created() {
    this.loadEmployes()
  },
  methods: {
    hRolesSuccessAssign() {
      this.roleShowDialog = false
    },
    // 角色分配
    hAssignRole(id) {
      this.roleShowDialog = true
      this.curId = id
      console.log(id, '------')
    },
    // 格式化数据转码
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const one = list[0]

      if (!one) return

      const hreads = Object.keys(one).map(item => {
        return map[item]
      })

      //   console.log(hreads)
      const data = list.map(item => {
        // console.log(item.formOfEmployment, '----------')
        const key = item.formOfEmployment
        item['formOfEmployment'] = hireType[key] || '未知'
        return Object.values(item)
      })
      // console.log(data,'dataaaaa');
      return { hreads, data }
    },
    // 导出excel下载下来
    // 思路
    // 1 - 发送请求获取数据
    // 2 - 将获取到的数据进行格式化处理,处理生产的excel文件需要的格式的数据(将英文转中文)
    // 3 - 调用admin 中关键的函数export_json_to_excel,生产excel文件
    async handleDownload() {
      // 1 - 发送请求获取数据
      try {
        const res = await getEmployes(this.page, this.size)
        const { hreads, data } = this.formatData(res.data.rows)
        // console.log(res.data.rows, '-----------------')
        // 2 - 将获取到的数据进行格式化处理,处理成生产excel文件需要的格式的数据
        // - header: ['中文的表头']
        // - data: [['一条数据的值'],[]]
        // 3 - 调用admin中关键的函数export_json_to_excel

        import('@/vendor/Export2Excel').then(excel => {
          excel.export_json_to_excel({
            header: hreads,
            data: data,
            filename: this.filename, // 文件名
            autoWidth: this.autoWidth, // 自动适配宽度
            bookType: this.bookType // 文件的类型
          })
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 删除员工
    async doDel(id) {
      await delEmployes(id)
      if (this.list.length === 1) this.page--
      if (this.page <= 0) this.page = 1
      this.loadEmployes()
    },
    hDel(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 关闭对话框 重置表单
    resetForm() {
      this.$refs.empFrom.resetForm()
    },
    // 分页器
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployes()
    },
    // 格式化应聘形式的函数
    formOfEmploymentFormat(id) {
      // return EmployessEnum.hireType.find(item => item.id === id).value
      return hireType[id] || '未知'
    },
    // 加载数据列表
    async loadEmployes() {
      try {
        const res = await getEmployes(this.page, this.size)
        this.list = res.data.rows
        this.total = res.data.total
        // console.log(res)
      } catch (error) {
        console.log(error)
      }
    },
    hCancel(id) {
      if (id === '1') {
        this.total++
        this.page = Math.ceil(this.total / this.size)
        this.loadEmployes()
      }
      this.showDialog = false
    }
  }
}
</script>
